package com.qixin.part.interceptor;

import com.qixin.api.bean.ComPtUser;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Zhang on 2018/8/26.
 */
public class Sessioninterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        ComPtUser comPtUser=(ComPtUser)session.getAttribute("user");
        if (session.getAttribute("user") != null&&comPtUser.getFlag().equals("1")){
//            System.out.println("request.getRequestURI()= "+request.getRequestURI());
            return true;
        } else {
           //当请求为数据库增删改的时候，跳转认证页面，或者先跳其他页面再跳
            if (session.getAttribute("user") != null&&!comPtUser.getFlag().equals("1")){

                if (request.getRequestURI().equals("/qinxin/car/add.html")||request.getRequestURI().equals("/qixin/comPeople/people_Add")) {
                    System.out.println("request.getRequestURI()= "+request.getRequestURI());
                  String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                  response.sendRedirect(basePath + "/comPtUser/Enterprise.html");
              }
            }

// if(request.getRequestURI().equals("/Zhang/motherNursing/editWord")){
//              }//                  return true;
            System.err.println("来了，老弟");
            redirect(request,response);
            return false;
        }
    }


    //对于请求是ajax请求重定向问题的处理方法
    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取当前请求的路径
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        // 如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理 否则直接重定向就可以了
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            //告诉ajax我是重定向
            response.setHeader("REDIRECT", "REDIRECT");
            // 告诉ajax我重定向的路径
            response.setHeader("CONTENTPATH", basePath + "/comPtUser/login.html");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            response.sendRedirect(basePath + "/comPtUser/login.html");
        }

    }
}

